/* 常用的工具类函数*/

// import common from "@/utils/jhTools"; //工具函数
import axios from "axios";
import API from "@/utils/api_config.js"; //引入api

//导入工具库
import lcT from "./lcT";
import lcM from "./lcM";
import lcRQ from "./lcRQ";
import { param } from "jquery";

// 目录
// LingChuang_request
// LingChuang_request_get



//领创函数集 post请求
var LingChuang_request = function () {

  var cPageUrl = "",
    cSearchUrl = "",
    cThis = "",
    searchData = {},
    initData = "",
    formatCallback = "";  //自定义格式化函数
  return function (opt) {
    cPageUrl = opt.pageUrl;
    cThis = opt.this;
    cSearchUrl = opt.searchUrl,
      searchData = opt.searchData ? opt.searchData : {
        pageIndex: 1,
        pageSize: 10
      };

    //初始请求
    function getInitData(data, callback, lastCb) {
      initData = data;
      console.log("分页p", data);
      formatCallback = callback,
        lastCb = lastCb || (() => { });
      post(
        cPageUrl,
        data,
        null,
        (res) => {
          console.log("分页res", res);
          if (res.code == 200) {
            if (res.data.records) {
              if (callback) {
                formatData(res, formatCallback);
              } else {
                formatData(res)
              }
              formatPaging(res);
              cThis.tableData = res.data.records;
              if (cThis.showPageKey) cThis.showPageKey++;

            } else if (res.data.length != undefined) {
              if (callback) {
                formatData2(res, formatCallback);
              } else {
                formatData2(res)
              }
              formatPaging(res);
              cThis.tableData = res.data;
              if (cThis.showPageKey) cThis.showPageKey++;

            } else {
              if (lastCb) lastCb(res);
              if (cThis.showPageKey) cThis.showPageKey++;
            }
          } else {
            console.log("请求错误：", res);
          }
        },
        (err) => {
          console.log(err);
        }
      );
    }

    // 封装
    function formatData(res, callback) {
      var resData = res.data.records || res.data;
      resData.forEach((item, index) => {
        item.index = index + 1;
      });
      if (callback) {
        callback(res, cThis);
      }
    }

    // 封装
    function formatData2(res, callback) {
      res.data.forEach((item, index) => {
        item.index = index + 1;
      });
      if (callback) {
        callback(res, cThis);
      }
    }

    // 分页格式化
    function formatPaging(res) {
      cThis.pageCount = Number(res.data.total); //总条数 //页面总条数自动计算
    }

    //每页条数切换
    function handleSizeChange(val) {
      cThis.onePageSize = val;
      getPagingData(cThis.currentPageIdx, cThis.onePageSize);
    }

    //分页跳转
    function handleCurrentChange(val) {
      console.log(val)
      cThis.currentPageIdx = val;
      getPagingData(cThis.currentPageIdx, cThis.onePageSize);
    }

    //enter触发分页输入框跳转
    function handleEnter(e) {
      getPagingData(cThis.currentPageIdx, cThis.onePageSize);
    }

    //分页数据
    function getPagingData(paging, size) {
      let url = cPageUrl;
      //带搜索参数
      var data = initData;
      for (var item in searchData) {
        data[item] = searchData[item];
      }
      data.pageIndex = paging;
      data.pageSize = size;
      console.log('参数', data);
      post(
        url,
        data,
        null,
        (res) => {
          if (res.code == 200) {
            console.log("分页数据成功", res);
            cThis.tableData = res.data.records;
            formatData(res, formatCallback);
            formatPaging(res);
            if (cThis.bindEvent) {
              cThis.bindEvent();
            }
          } else { }
        },
        (err) => {
          console.log(err);
        }
      );
    }

    //列表勾选1
    function toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          cThis.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        cThis.$refs.multipleTable.clearSelection();
      }
    }
    //列表勾选2
    function handleSelectionChange(val) {
      cThis.multipleSelection = val;
    }

    //省份
    function getProvince(opt) {
      var urlP = opt.url,
        tThis = opt.tThis;
      const paramP = {};
      console.log("参数省份", paramP);
      common.get(
        urlP,
        paramP,
        null,
        (res) => {
          console.log("获取省份", res);
          console.log(tThis.cityData)
          tThis.cityData = res.data;
          var newOptions = [];
          tThis.cityData.forEach((item, index) => {
            newOptions.push({
              value: item.id,
              label: item.name,
            });
          });
          tThis.provinceOptions = newOptions;
        },
        (err) => {
          console.log(err);
        }
      );
    }

    // res.data.data.child  province

    //省份联动
    function handleProvinceChange(opt) {
      var tThis = opt.tThis,
        provinceIdName = opt.provinceIdName,
        url = opt.url + tThis.formData[provinceIdName],
        cityOptsName = opt.cityOptsName,
        cityIdName = opt.cityIdName;
      cThis.formData[cityIdName] = "";

      const param = {
        parentId: tThis.formData[provinceIdName]
      };
      // console.log("参数", param);
      common.get(
        url,
        null,
        param,
        (res) => {
          // console.log("市联动", res);
          tThis.cityData = res.data.data.child;
          var newOptions = [];
          tThis.cityData.forEach((item, index) => {
            newOptions.push({
              value: item.id,
              label: item.name,
              areaList: item.child,
            });
          });
          tThis[cityOptsName] = newOptions;
        },
        (err) => {
          console.log(err);
        }
      );
    }

    //res.data.data


    //市区联动
    function handleCityChange(opt) {
      var tThis = opt.tThis,
        cityIdName = opt.cityIdName,
        cityId = tThis.formData[cityIdName],
        curCityIndex = 0,
        regionOptsName = opt.regionOptsName,
        regionIdName = opt.regionIdName;
      // tThis.formData[regionIdName] = "";
      var newOptions = [];
      for (var i = 0; i < tThis.cityData.length; i++) {
        var item = tThis.cityData[i];
        if (item.id == cityId) {
          curCityIndex = i;
          break;
        }
      }
      tThis.cityData[curCityIndex].child.forEach((item, index) => {
        newOptions.push({
          value: item.id,
          label: item.name,
        });
      });
      tThis[regionOptsName] = newOptions;
    }

    //查找
    function handleSearch(sData) {
      let url = cSearchUrl;
      searchData = sData ? sData : searchData;  //当前查询条件，覆盖初始查询条件
      let data = searchData;
      console.log("查询p", data);
      post(
        url,
        data,
        null,
        (res) => {
          console.log('查询结果', res)
          if (res.code == "200") {
            //格式化数据
            formatData(res, formatCallback);
            formatPaging(res);
            if (res.data.records && res.data.records.length == 0) {
              //提示
              cThis.$message({
                type: "error",
                message: "暂无数据!"
              });
              cThis.tableData = [];
              return;
            }
            //赋值操作
            if (res.data.records) {
              cThis.tableData = res.data.records;
            } else if (res.data) {

              cThis.tableData = res.data;
            }
            //提示
            cThis.$message({
              type: "success",
              message: "查询成功!"
            });
          } else {
            //提示
            cThis.$message({
              type: "error",
              message: "请求错误!"
            });
          }
        },
        (err) => {
          console.log(err);
        }
      );
    }

    //刷新页面
    function handleSearchRefresh(sData) {
      let url = cSearchUrl;
      searchData = sData ? sData : searchData;
      let data = searchData;
      console.log("参数", data);
      common.post(
        url,
        data,
        null,
        (res) => {
          console.log('查询结果', res)
          if (res.code == "200") {
            cThis.tableData = res.data.records;
            //格式化数据
            formatData(res, formatCallback);
            formatPaging(res);
            if (res.data.records.length == 0) {
              //提示
              cThis.$message({
                type: "error",
                message: "暂无数据!"
              });
              return;
            }
          } else {
            //提示
            cThis.$message({
              type: "error",
              message: "请求错误!"
            });
          }
        },
        (err) => {
          console.log(err);
        }
      );
    }

    //获取详情
    function handleGetDetail(opt) {
      var url = opt.url,
        data = opt.data,
        successCb = opt.successCb ? opt.successCb : (() => { });
      console.log("参数", data);
      common.get(
        url,
        data,
        null,
        (res) => {
          console.log("获取数据详情", res);
          if (res.code == 200) {
            for (var item in res.data) {
              cThis.formData[item] = res.data[item];
            }
            successCb(res);
          } else {
            cThis.$message({
              type: "error",
              message: "数据获取失败"
            })
          }
        },
        (err) => {
          console.log(err);
        }
      );
    }

    //编辑
    function handleEdit(opt) {
      var url = opt.url,
        dataArr = opt.dataArr,
        myData = opt.myData; //自定义数据
      console.log("参数", data);
      for (var i = 0; i < dataArr.length; i++) {
        var item = dataArr[i];
        if (!cThis.formData[item]) {
          alert("输入不能为空!");
          return;
        }
      }
      var data = {};
      for (var i = 0; i < dataArr.length; i++) {
        var item = dataArr[i];
        data[item] = cThis.formData[item] ? cThis.formData[item] : undefined;
      }
      for (var item in myData) {
        data[item] = myData[item];
      }
      console.log('编辑参数', data);
      common.post(
        url,
        data,
        null,
        (res) => {
          console.log("结果", res);
          cThis.$message({
            type: "success",
            message: "操作成功",
          });
          cThis.isOpenModel = false;
          handleSearchRefresh();
        },
        (err) => {
          console.log(err);
        }
      );
    }
    //删除
    function handleDelete(opt) {
      var url = opt.url,
        data = opt.data ? opt.data : {};
      cThis.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          console.log('编辑参数', data);
          common.post(
            url,
            data,
            null,
            (res) => {
              console.log("结果", res);
              console.log(res);
              if (res.message == "操作成功") {
                cThis.$message({
                  type: "success",
                  message: "删除成功!"
                });
                handleSearchRefresh();
              }
            },
            (err) => {
              console.log(err);
            }
          );
        })
        .catch(err => {
          console.log(err);
          cThis.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    }

    //添加
    function handleAdd(opt) {
      var url = opt.url,
        dataArr = opt.dataArr,
        successCb = opt.successCb,
        myData = opt.myData, //预留自定义添加数据data
        isGetTable = opt.isGetTable,
        jumpPath = opt.jumpPath;
      console.log(jumpPath)
      for (var i = 0; i < dataArr.length; i++) {
        var item = dataArr[i];
        if (!cThis.formData[item]) {
          alert(item + "输入不能为空!");
          return;
        }
      }
      var data = {};
      for (var i = 0; i < dataArr.length; i++) {
        var item = dataArr[i];
        data[item] = cThis.formData[item] ? cThis.formData[item] : undefined;
      }
      for (var item in myData) {
        data[item] = myData[item];
      }
      console.log("参数", data);
      common.post(
        url,
        data,
        null,
        (res) => {
          console.log("结果", res);
          if (res.code == 200) {
            cThis.$message({
              type: "success",
              message: "操作成功",
            });
            cThis.isOpenModel = false;
            isGetTable && cThis.getInitData();
            if (jumpPath) {
              cThis.$router.push({
                path: jumpPath
              });
            }
            successCb();
          }
        },
        (err) => {
          console.log(err);
        }
      );
    }
    //启用

    //禁用

    //图片上传
    function uploadImgFirst(file, successCb) {
      console.log("图片文件", file); //腾讯云cos上传
      var url = API.common.img_upload + "jpeg";
      var pm = new Promise((resolve, reject) => {
        axios.get(url, {}, {
          "Content-Type": "multipart/form-data"
        }).then(
          (res) => {
            console.log("上传链接", res);
            resolve({
              uploadUrl: res.data.data.uploadUrl,
              downloadUrl: res.data.data.downloadUrl,
              fileKey: res.data.data.fileKey,
            });
          },
          (err) => {
            console.log(err);
            reject(err);
          }
        );
      }).then((uploadObj) => {
        axios
          .put(uploadObj.uploadUrl, file, {
            "Content-Type": "multipart/form-data",
          })
          .then(
            (res) => {
              console.log("上传结果", res);
              successCb(res, uploadObj);
              console.log(uploadObj, cThis.imgUrl);
            },
            (err) => {
              console.log(err);
            }
          );
      });
    }

    //上传成功
    function handleAvatarSuccess(res, file) {
      cThis.$message({
        type: "success",
        message: "上传成功",
      });
    }

    return {
      getInitData,
      getPagingData,
      formatPaging,
      handleSizeChange,
      handleCurrentChange,
      handleEnter,
      toggleSelection,
      handleSelectionChange,
      handleSearch,
      handleEdit,
      handleAdd,
      uploadImgFirst,
      handleAvatarSuccess,
      handleGetDetail,
      handleDelete,
      getProvince, //获取省份
      handleProvinceChange, //省份联动
      handleCityChange, //市区联动
    }
  }
}();


//get请求
var LingChuang_request_get = function () {
  var cPageUrl = "",
    cSearchUrl = "",
    cThis = "",
    searchData = {},
    initData = "",
    formatCallback = "";  //自定义格式化函数

  return function (opt) {
    cPageUrl = opt.pageUrl;
    cThis = opt.this;
    cSearchUrl = opt.searchUrl,
      searchData = opt.searchData ? opt.searchData : {
        pageIndex: 1,
        pageSize: 10
      };

    //初始请求
    function getInitData(data, callback) {
      initData = data;
      console.log("传参", data);
      formatCallback = callback;
      get(
        cPageUrl,
        null,
        data,
        (res) => {
          console.log("返回结果", res);
          if (res.code == 200) {
            if (res.data.records) {
              if (callback) {
                formatData(res, formatCallback);
              } else {
                formatData(res)
              }
              formatPaging(res);
              cThis.tableData = res.data.records;
            } else if (res.data.length != undefined) {
              if (callback) {
                formatData2(res, formatCallback);
              } else {
                formatData2(res)
              }
              formatPaging(res);
              cThis.tableData = res.data;
            }
          } else {
            console.log("请求错误：", res);
          }
        },
        (err) => {
          console.log(err);
        }
      );
    }

    // 格式化
    function formatData(res, callback) {
      res.data.forEach((item, index) => {
        item.index = index + 1;
      });
      if (callback) {
        callback(res, cThis);
      }
    }

    // 格式化2
    function formatData2(res, callback) {
      res.data.forEach((item, index) => {
        item.index = index + 1;
      });
      if (callback) {
        callback(res, cThis);
      }
    }

    // 分页格式化
    function formatPaging(res) {
      cThis.pageCount = Number(res.data.total); //总条数 //页面总条数自动计算
    }

    //每页条数切换
    function handleSizeChange(val) {
      cThis.onePageSize = val;
      getPagingData(cThis.currentPageIdx, cThis.onePageSize);
    }

    //分页跳转
    function handleCurrentChange(val) {
      console.log(val)
      cThis.currentPageIdx = val;
      getPagingData(cThis.currentPageIdx, cThis.onePageSize);
    }

    //enter触发分页输入框跳转
    function handleEnter(e) {
      getPagingData(cThis.currentPageIdx, cThis.onePageSize);
    }

    //分页数据
    function getPagingData(paging, size) {
      let url = cPageUrl;
      //带搜索参数
      var data = initData;
      for (var item in searchData) {
        data[item] = searchData[item];
      }
      data.pageIndex = paging;
      data.pageSize = size;
      console.log('参数', data);
      get(
        url,
        null,
        data,
        (res) => {
          if (res.code == 200) {
            console.log("分页数据成功", res);
            cThis.tableData = res.data;
            formatData(res, formatCallback);
            formatPaging(res);
          } else { }
        },
        (err) => {
          console.log(err);
        }
      );
    }

    //列表勾选1
    function toggleSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          cThis.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        cThis.$refs.multipleTable.clearSelection();
      }
    }
    //列表勾选2
    function handleSelectionChange(val) {
      cThis.multipleSelection = val;
    }

    //省份
    function getProvince(opt) {
      var urlP = opt.url,
        tThis = opt.tThis;
      const paramP = {};
      console.log("参数省份", paramP);
      common.get(
        urlP,
        paramP,
        null,
        (res) => {
          console.log("获取省份", res);
          console.log(tThis.cityData)
          tThis.cityData = res.data;
          var newOptions = [];
          tThis.cityData.forEach((item, index) => {
            newOptions.push({
              value: item.id,
              label: item.name,
            });
          });
          tThis.provinceOptions = newOptions;
        },
        (err) => {
          console.log(err);
        }
      );
    }

    // res.data.data.child  province

    //省份联动
    function handleProvinceChange(opt) {
      var tThis = opt.tThis,
        provinceIdName = opt.provinceIdName,
        url = opt.url + tThis.formData[provinceIdName],
        cityOptsName = opt.cityOptsName,
        cityIdName = opt.cityIdName;
      cThis.formData[cityIdName] = "";

      const param = {
        parentId: tThis.formData[provinceIdName]
      };
      // console.log("参数", param);
      common.get(
        url,
        null,
        param,
        (res) => {
          // console.log("市联动", res);
          tThis.cityData = res.data.data.child;
          var newOptions = [];
          tThis.cityData.forEach((item, index) => {
            newOptions.push({
              value: item.id,
              label: item.name,
              areaList: item.child,
            });
          });
          tThis[cityOptsName] = newOptions;
        },
        (err) => {
          console.log(err);
        }
      );
    }

    //res.data.data


    //市区联动
    function handleCityChange(opt) {
      var tThis = opt.tThis,
        cityIdName = opt.cityIdName,
        cityId = tThis.formData[cityIdName],
        curCityIndex = 0,
        regionOptsName = opt.regionOptsName,
        regionIdName = opt.regionIdName;
      // tThis.formData[regionIdName] = "";
      var newOptions = [];
      for (var i = 0; i < tThis.cityData.length; i++) {
        var item = tThis.cityData[i];
        if (item.id == cityId) {
          curCityIndex = i;
          break;
        }
      }
      tThis.cityData[curCityIndex].child.forEach((item, index) => {
        newOptions.push({
          value: item.id,
          label: item.name,
        });
      });
      tThis[regionOptsName] = newOptions;
    }

    //查找
    function handleSearch(sData) {
      let url = cSearchUrl;
      searchData = sData ? sData : searchData;  //当前查询条件，覆盖初始查询条件
      let data = searchData;
      console.log("查询p", data);
      post(
        url,
        data,
        null,
        (res) => {
          console.log('查询结果', res)
          if (res.code == "200") {
            cThis.tableData = res.data;
            //格式化数据
            formatData(res, formatCallback);
            formatPaging(res);
            if (res.data.length == 0) {
              //提示
              cThis.$message({
                type: "error",
                message: "暂无数据!"
              });
              return;
            }
            //提示
            cThis.$message({
              type: "success",
              message: "查询成功!"
            });
          } else {
            //提示
            cThis.$message({
              type: "error",
              message: "请求错误!"
            });
          }
        },
        (err) => {
          console.log(err);
        }
      );
    }

    //刷新页面
    function handleSearchRefresh(sData) {
      let url = cSearchUrl;
      searchData = sData ? sData : searchData;
      let data = searchData;
      console.log("参数", data);
      common.post(
        url,
        data,
        null,
        (res) => {
          console.log('查询结果', res)
          if (res.code == "200") {
            cThis.tableData = res.data.records;
            //格式化数据
            formatData(res, formatCallback);
            formatPaging(res);
            if (res.data.length == 0) {
              //提示
              cThis.$message({
                type: "error",
                message: "暂无数据!"
              });
              return;
            }
          } else {
            //提示
            cThis.$message({
              type: "error",
              message: "请求错误!"
            });
          }
        },
        (err) => {
          console.log(err);
        }
      );
    }

    //获取详情
    function handleGetDetail(opt) {
      var url = opt.url,
        data = opt.data,
        successCb = opt.successCb ? opt.successCb : (() => { });
      console.log("参数", data);
      common.get(
        url,
        data,
        null,
        (res) => {
          console.log("获取数据详情", res);
          if (res.code == 200) {
            for (var item in res.data) {
              cThis.formData[item] = res.data[item];
            }
            successCb(res);
          } else {
            cThis.$message({
              type: "error",
              message: "数据获取失败"
            })
          }
        },
        (err) => {
          console.log(err);
        }
      );
    }

    //编辑
    function handleEdit(opt) {
      var url = opt.url,
        dataArr = opt.dataArr,
        myData = opt.myData; //自定义数据
      console.log("参数", data);
      for (var i = 0; i < dataArr.length; i++) {
        var item = dataArr[i];
        if (!cThis.formData[item]) {
          alert("输入不能为空!");
          return;
        }
      }
      var data = {};
      for (var i = 0; i < dataArr.length; i++) {
        var item = dataArr[i];
        data[item] = cThis.formData[item] ? cThis.formData[item] : undefined;
      }
      for (var item in myData) {
        data[item] = myData[item];
      }
      console.log('编辑参数', data);
      common.post(
        url,
        data,
        null,
        (res) => {
          console.log("结果", res);
          cThis.$message({
            type: "success",
            message: "操作成功",
          });
          cThis.isOpenModel = false;
          handleSearchRefresh();
        },
        (err) => {
          console.log(err);
        }
      );
    }
    //删除
    function handleDelete(opt) {
      var url = opt.url,
        data = opt.data ? opt.data : {};
      cThis.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          console.log('编辑参数', data);
          common.post(
            url,
            data,
            null,
            (res) => {
              console.log("结果", res);
              console.log(res);
              if (res.message == "操作成功") {
                cThis.$message({
                  type: "success",
                  message: "删除成功!"
                });
                handleSearchRefresh();
              }
            },
            (err) => {
              console.log(err);
            }
          );
        })
        .catch(err => {
          console.log(err);
          cThis.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    }

    //添加
    function handleAdd(opt) {
      var url = opt.url,
        dataArr = opt.dataArr,
        successCb = opt.successCb,
        myData = opt.myData, //预留自定义添加数据data
        isGetTable = opt.isGetTable,
        jumpPath = opt.jumpPath;
      console.log(jumpPath)
      for (var i = 0; i < dataArr.length; i++) {
        var item = dataArr[i];
        if (!cThis.formData[item]) {
          alert(item + "输入不能为空!");
          return;
        }
      }
      var data = {};
      for (var i = 0; i < dataArr.length; i++) {
        var item = dataArr[i];
        data[item] = cThis.formData[item] ? cThis.formData[item] : undefined;
      }
      for (var item in myData) {
        data[item] = myData[item];
      }
      console.log("参数", data);
      common.post(
        url,
        data,
        null,
        (res) => {
          console.log("结果", res);
          if (res.code == 200) {
            cThis.$message({
              type: "success",
              message: "操作成功",
            });
            cThis.isOpenModel = false;
            isGetTable && cThis.getInitData();
            if (jumpPath) {
              cThis.$router.push({
                path: jumpPath
              });
            }
            successCb();
          }
        },
        (err) => {
          console.log(err);
        }
      );
    }
    //启用

    //禁用

    //图片上传
    function uploadImgFirst(file, successCb) {
      console.log("图片文件", file); //腾讯云cos上传
      var url = API.common.img_upload + "jpeg";
      var pm = new Promise((resolve, reject) => {
        axios.get(url, {}, {
          "Content-Type": "multipart/form-data"
        }).then(
          (res) => {
            console.log("上传链接", res);
            resolve({
              uploadUrl: res.data.data.uploadUrl,
              downloadUrl: res.data.data.downloadUrl,
              fileKey: res.data.data.fileKey,
            });
          },
          (err) => {
            console.log(err);
            reject(err);
          }
        );
      }).then((uploadObj) => {
        axios
          .put(uploadObj.uploadUrl, file, {
            "Content-Type": "multipart/form-data",
          })
          .then(
            (res) => {
              console.log("上传结果", res);
              successCb(res, uploadObj);
              console.log(uploadObj, cThis.imgUrl);
            },
            (err) => {
              console.log(err);
            }
          );
      });
    }

    //上传成功
    function handleAvatarSuccess(res, file) {
      cThis.$message({
        type: "success",
        message: "上传成功",
      });
    }

    return {
      getInitData,
      getPagingData,
      formatPaging,
      handleSizeChange,
      handleCurrentChange,
      handleEnter,
      toggleSelection,
      handleSelectionChange,
      handleSearch,
      handleEdit,
      handleAdd,
      uploadImgFirst,
      handleAvatarSuccess,
      handleGetDetail,
      handleDelete,
      getProvince, //获取省份
      handleProvinceChange, //省份联动
      handleCityChange, //市区联动
    }
  }
}();



//公共工具方法
var Vue = require('vue');
// Vue.http.options.credentials = true;


/* post请求，添加token */
function post(url, param, dataForm = null, callBack, failBack = null, _this, config) {
  let sessionId = sessionStorage.getItem('sessionId');
  let sendUrl = url;
  var isConfig = config;
  let searchStr = "";

  var noParams = "";
  var isSetSearchStr = true;
  if (config) {
    noParams = config.noParams;
    isSetSearchStr = config.isSetSearchStr == "false" ? false : true;
  }

  //拼接查询字符串
  if (isSetSearchStr) {
    //不编入链接的字段
    var noSearchUrl = [
      "introduction",
    ];

    if (noParams) {
      noSearchUrl = noParams;
    }

    if (!dataForm) {
      dataForm = param;
    }
    for (let item in dataForm) {
      noSearchUrl.forEach((nItem, index) => {
        if (typeof dataForm[item] == 'string') {
          if (item != nItem && (dataForm[item].length < 30)) {
            searchStr += "&" + item + '=' + dataForm[item];
          }
        } else if (typeof dataForm[item] == 'object') {
          console.log(dataForm[item]);
        } else {
          if (item != nItem) {
            searchStr += "&" + item + '=' + dataForm[item];
          }
        }

      })
    }
    if (dataForm) {
      var searchStrArr = searchStr.split('');
      searchStrArr[0] = "?";
      searchStr = searchStrArr.join("");
    }
    sendUrl += searchStr;
  }


  // console.log("参数", param || dataForm);
  Vue.default.http.post(sendUrl, param, {
    headers: {
      sessionId: sessionId,
    }
  }).then(res => {
    // console.log("结果", res);
    //登录过期判断
    if (res.body.code == 401 && res.body.message == "未登录或token失效") {
      console.log('登录已过期');
      sessionStorage.removeItem('sessionId');
      location.href = "./#/login"; //注意修改的路径
      location.reload();
      return;
    } else if (res.body.code != 200) {
      console.error(res.body.message)
      lcM.Model({
        msg: res.body.message,
      });
    }
    //成功回调
    callBack(res.body)
  }, res => {
    // alert(res.body.message);
    console.log("error", res.body.message)
    if (failBack) {
      failBack(res.body);
    }
  });
}



/* get请求，添加token权限 */
function get(url, param, dataForm = null, callBack, failBack = null) {
  let sessionId = sessionStorage.getItem('sessionId');
  let sendUrl = url;
  var sStr = "";

  //赋值
  if(!param && dataForm) param = dataForm;
  if(!dataForm && param) dataForm = param;

  for (let item in dataForm) {
    sStr += "&" + item + '=' + dataForm[item];
  }
  var sStrArr = sStr.split('');
  if (sStrArr[0]) sStrArr[0] = "?";
  sStr = sStrArr.join("");
  sendUrl += sStr;
  $.ajax({
    type: 'GET',
    url: sendUrl,
    headers: {
      sessionId: sessionId,
      "Content-Type": "application/json;charset=UTF-8"
    },
    success: function (res) {
      console.log("结果结果", res);
      //登录过期判断
      if (res.code == 401 || res.message == "未登录或token失效") {
        console.log('登录已过期');
        sessionStorage.removeItem('sessionId');
        location.href = "./#/login";
        location.reload();
        return;
      }
      //成功回调
      callBack(res)
    },
    error: function (err) {
      // alert(res.body.message);
      console.log("error", res.message)
      failBack(err)
    }
  })

  // //post请求，添加token 冰棍
  // function post(url, param, dataForm = null, callBack, failBack = null) {
  //   let token = sessionStorage.getItem('token');
  //   let sendUrl = url;
  //   for (let item in dataForm) {
  //     sendUrl = sendUrl + "?" + item + '=' + dataForm[item];
  //   }
  //   Vue.default.http.post(sendUrl, param, {
  //     headers: {
  //       token: token
  //     }
  //   }).then(res => {
  //     callBack(res.body)
  //   }, res => {
  //     if (failBack) {
  //       failBack(res.body)
  //     }
  //   });
  // }



  // //get请求，添加token权限 冰棍
  // function get(url, param, dataForm = null, callBack, failBack = null) {
  //   let token = sessionStorage.getItem('token');
  //   let sendUrl = url;
  //   for (let item in dataForm) {
  //     sendUrl = sendUrl + "?" + item + '=' + dataForm[item];
  //   }
  //   $.ajax({
  //     type: 'GET',
  //     url: sendUrl,
  //     headers: {
  //       token: token,
  //       "Content-Type": "application/json;charset=UTF-8"
  //     },
  //     success: function (res) {
  //       // console.log(res);
  //       callBack(res)
  //     },
  //     error: function (err) {
  //       // console.log(err)
  //       failBack(err)
  //     }
  //   })

  // Vue.default.http.get(sendUrl, {
  //   headers: {
  //     'token': token
  //   },
  //   emulateJSON: true,
  //   credentials: true
  // }).then(res => {
  //   callBack(res.body)
  // }, res => {
  //   if (failBack) {
  //     failBack(res.body)
  //   }
  // })

}


/* 贺工请求设置 直接发送和返回 */
function post2({ url, params, success = () => { }, fail = () => { } }) {
  return new Promise((resolve, reject) => {
    // console.log("参数", param || dataForm);
    var sUrlStr = "";
    if (params) {
      for (var itemKey in params) {
        // sUrlStr += "&" + itemKey + "=" + params[itemKey];
        if (typeof params[itemKey] == 'string') {
          if (params[itemKey].length < 30) {
            sUrlStr += "&" + itemKey + '=' + params[itemKey];
          }
        } else if (typeof params[itemKey] == 'object') {
          console.log(params[itemKey]);
        } else {
          sUrlStr += "&" + itemKey + '=' + params[itemKey];
        }
      }
      if (sUrlStr.length > 0) {
        let sArr = sUrlStr.split("");
        sArr[0] = "?";
        sUrlStr = sArr.join("");
      }

    }
    url += sUrlStr;
    Vue.default.http.post(
      url,
      params,
      {
        headers: {
          sign: "a54475b53fa214bff196f1a234a3f16e",
          timestamp: "1577811661000",
        }
      }
    ).then(res => {
      resolve(res);
      success(res);
    }, err => {
      fail(err);
      reject(err);
    });
  });

  /* 
      this.tools.post2({
        url: this.api2.jd_order.jd_make_order,
        params: {
          id,
        },
        success: res => {
          
        }
      })
  
  */
}


/* 表单提交 */
function formSubmit(url, param, callBack, failBack = null) {
  Vue.default.http.post(url, param, {
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    emulateJSON: true
  }).then(res => {
    callBack(res.data)
  }, res => {
    if (failBack) {
      failBack(res.data)
    }
  });
}

/* 文件上传 */
function uploadFile(url, param, contentType, callBack, failBack = null) { // 上传图片到阿里云
  Vue.default.http.put(url, param, {
    headers: {
      'Content-Type': contentType
    },
    emulateJSON: false
  }).then(res => {
    callBack(res.data)
  }, res => {
    if (failBack) {
      failBack(res.data)
    }
  });
}

function setCookie(name, value) {
  var Days = 2;
  var exp = new Date();
  exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
  // document.cookie = name + "=" + escape(value) ;
  document.cookie = name + "=" + escape(value) + ";path=/;expires=" + exp.toGMTString();
}

//读取cookie：
function getCookie(name) {
  var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
  return (arr = document.cookie.match(reg)) ? unescape(arr[2]) : null;
}

//检查输入非空和组合参数data
function checkInputTool(opt) {
  var tThis = opt.tThis,
    dataArr = opt.dataArr,
    tipsObj = opt.tipsObj;
  var data = {};
  for (var i = 0; i < dataArr.length; i++) {
    var item = dataArr[i];
    if (!tThis[item]) {
      if (tipsObj) {
        tThis.$alert(tipsObj[item] + '不能为空', "提示", {
          confirmButtonText: "确定",
          callback: (action) => { },
        });
      } else {
        tThis.$alert(item + '输入不能为空', "提示", {
          confirmButtonText: "确定",
          callback: (action) => { },
        });
      }
      return false;
    }
    data[item] = tThis[item];
  }
  return data;
}


//检查输入非空和组合参数data
function checkInputFormDataTool(opt) {
  var tThis = opt.tThis,
    dataArr = opt.dataArr,
    tipsObj = opt.tipsObj;
  var data = {};
  for (var i = 0; i < dataArr.length; i++) {
    var item = dataArr[i];
    //console.log(tipsObj[item]+ ":" + tThis.formData[item]);
    if (!tThis.formData[item]) {
      if (tipsObj) {
        tThis.$alert(tipsObj[item] + '不能为空', "提示", {
          confirmButtonText: "确定",
          callback: (action) => { },
        });
      } else {
        tThis.$alert(item + '输入不能为空', "提示", {
          confirmButtonText: "确定",
          callback: (action) => { },
        });
      }
      return false;
    }
    data[item] = tThis.formData[item];
  }
  return data;

}

//清空
function handleClear(opt) {
  var tThis = opt.tThis,
    dataArr = opt.dataArr;
  dataArr.forEach((item, index) => {
    tThis.formData[item] = '';
  })
}



/* post请求，添加token */
function directPost({
  url, params, success = () => { }, fail = () => { }
}) {
  let callBack = success;
  let failBack = fail;
  let dataForm = {};
  dataForm = params; //post请求中
  let sessionId = sessionStorage.getItem('sessionId');
  let sendUrl = url;
  let searchStr = "";
  for (let item in dataForm) {
    searchStr += "&" + item + '=' + dataForm[item];
  }
  if (dataForm) {
    var searchStrArr = searchStr.split('');
    searchStrArr[0] = "?";
    searchStr = searchStrArr.join("");
  }
  //拼接查询字符串
  sendUrl += searchStr;
  Vue.default.http.post(sendUrl, params, {
    headers: {
      sessionId: sessionId || ""
    }
  }).then(res => {
    console.log("成功结果", res);
    callBack(res.body) //成功回调
  }, res => {
    // alert(res.body.message);
    console.log("失败结果", res)
    if (failBack) {
      failBack(res.body);
    }
  });

  /* 
    调用
    let url = API.profit_rec_m.detail;
    let data = {
        id,
      };
    console.log("参数", data);
    jhTools.get(
      url,
      null, 
      data,
      (res) => {
        console.log("结果", res);
        if (res.code == 200) {
         this.formData = res.data;
        }
      },
      (err) => {
        console.log(err);
      }
    );
  
  */
}



/* post请求，添加token */
function directGet({
  url, params, success = () => { }, fail = () => { }
}) {
  let callBack = success;
  let failBack = fail;
  let dataForm = {};
  dataForm = params; //post请求中
  let sessionId = sessionStorage.getItem('sessionId');
  let sendUrl = url;
  // let searchStr = "";
  // for (let item in dataForm) {
  //   searchStr += "&" + item + '=' + dataForm[item];
  // }
  // if(dataForm) {
  //   var searchStrArr = searchStr.split('');
  //   searchStrArr[0] = "?";
  //   searchStr = searchStrArr.join("");
  // }
  // //拼接查询字符串
  // sendUrl += searchStr;
  $.ajax({
    type: 'GET',
    url: sendUrl,
    data: params,
    headers: {
      sessionId: sessionId,
      "Content-Type": "application/json;charset=UTF-8"
    },
    success: function (res) {
      console.log("成功结果", res);
      callBack(res) //成功回调
    },
    error: function (err) {
      console.log("失败结果", res)
      if (failBack) {
        failBack(res);
      }
    }
  })

  /* 
    调用
    let url = API.profit_rec_m.detail;
    let data = {
        id,
      };
    console.log("参数", data);
    jhTools.directGet(
      {
        url: this.tools.admin.aa, 
        params: {}, 
        success: ()=> {

        }, 
        fail: ()=> {

        }
      }
    );
  
  */
}


function basePost({
  _this,
  url,
  params,
  success,
  fail,
}) {
  var opts = {
    url,
    param: params,
    dataForm: params,
    callBack: success,
    failBack: fail,
    _this,
  }
  post(opts.url, opts.param, opts.dataForm, opts.callBack, opts.failBack, opts._this);
  /* 
    this.tools.basePost({
      url: this.api.jd_m.pxSync,
          params: {
            ids: idsStr
          },
          success: (res) => {
            if(res.code == 200) {
              this.tools.Model({
                msg: res.message
              });
            }
          },
          fail: (err) => {},
    });
  
  */
}


function baseGet({
  _this,
  url,
  params,
  success,
  fail,
}) {
  var opts = {
    url,
    param: params,
    dataForm: params,
    callBack: success,
    failBack: fail,
    _this,
  }
  get(opts.url, opts.param, opts.dataForm, opts.callBack, opts.failBack, opts._this);
  /* 
      this.tools.baseGet({
          url: this.api.jd_m.pxSync,
          params: {
            ids: idsStr
          },
          success: (res) => {
            if(res.code == 200) {
              this.tools.Model({
                msg: res.message
              });
            }
          },
          fail: (err) => {},
        });
  */

}

export default {
  post: post,
  get: get,
  getCookie: getCookie,
  uploadFile: uploadFile,
  formSubmit: formSubmit,

  directPost, //直接请求，不做登录过期校验。有sessionId就携带
  directGet,
  basePost,
  baseGet,

  LingChuang_request, //领创请求集 post分页
  LingChuang_request_get, //领创请求集 get分页
  // BingGun_request, //冰棍请求集

  //工具类
  checkInputTool, //检查输入 无formData
  checkInputFormDataTool, //检查表单 有formData
  handleClear, //清空

  ...lcT, //领创通用库
  ...lcM, //领创后台管理库
  ...lcRQ, //项目请求库

  post2, //贺工的post请求
}


